package secondwork;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.cj.Session;

/**
 * Servlet implementation class CookieServlet
 */
@WebServlet(name = "ck", urlPatterns = { "/ck" })
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		Cookie[] cks = req.getCookies();
		if (cks != null) {
			String name = "";
			for (Cookie c : cks) {
				if ("name".equals(c.getName())) {
					name = c.getValue();
				}
			}
			if ("".equals(name)) {
				req.getRequestDispatcher("/login2.html").forward(req, resp);
				return;
			} else {
				HttpSession session = req.getSession(); // request是HttpServletRequest类型的
				session.setAttribute("name", name);
				resp.sendRedirect("/demo/main.jsp");
			}
		} else {
			req.getRequestDispatcher("/login2.html").forward(req, resp);
			return;
		}
	}
}
